//
//  MJ_UserMessage.m
//  UEAssistant
//
//  Created by mac on 2017/12/28.
//  Copyright © 2017年 youyixinxi. All rights reserved.
//

#import "MJ_UserMessage.h"
#import "MessageViewController.h"
#import <UIViewController+MMDrawerController.h>
#import "TabbarController.h"
#import "LeftSortsViewController.h"
#import "MJ_TaskViewController.h"
#import "NavigationController.h"
#import "UIViewController+CurrentController.h"
#import "UIView+Badge.h"
#import "MJResultModel.h"
#import "MJVersionCheckModel.h"
@interface MJ_UserMessage ()
@end

@implementation MJ_UserMessage

#pragma mark -- 懒加载
- (NSString *)baseUrl {
    if (!_baseUrl) {
        _baseUrl = BASE_URL_INTERNET;
    }
    return _baseUrl;
}
- (UIButton *)userHeadButton {
    if (!_userHeadButton) {
        _userHeadButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _userHeadButton.frame = CGRectMake(16, 8, 28, 28);
        [_userHeadButton setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:shareData.headURL] placeholderImage:[UIImage imageNamed:@"user"]];
        _userHeadButton.layer.cornerRadius = 14;
        _userHeadButton.layer.masksToBounds = YES;
        [_userHeadButton addTarget:self action:@selector(openLeftController) forControlEvents:UIControlEventTouchUpInside];
    }
    return _userHeadButton;
}
- (UIButton *)messageBarButton {
    if (!_messageBarButton) {
        _messageBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_messageBarButton setImage:[UIImage imageNamed:@"消息"] forState:UIControlStateNormal];
        _messageBarButton.frame = CGRectMake(Screen_Width - 44, 0, 44, 44);
        [_messageBarButton addTarget:self action:@selector(message) forControlEvents:UIControlEventTouchUpInside];
    }
    return _messageBarButton;
}
- (UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc]initWithFrame:CGRectMake(7*Radio, iPhoneX ? 15*Radio-3 : 15*Radio-1, 2.6, 2.6)];
        _topView.backgroundColor = RGB(134, 137, 147, 1);
        _topView.layer.cornerRadius = 1.3;
        _topView.layer.masksToBounds = YES;
    }
    return _topView;
}

- (UIView *)midView {
    if (!_midView) {
        _midView = [[UIView alloc]initWithFrame:CGRectMake(7*Radio, iPhoneX ? 25*Radio-4 : 25*Radio-2, 2.6, 2.6)];
        _midView.backgroundColor = RGB(134, 137, 147, 1);
        _midView.layer.cornerRadius = 1.3;
        _midView.layer.masksToBounds = YES;
    }
    return _midView;
}

- (UIView *)footView {
    if (!_footView) {
        _footView = [[UIView alloc]initWithFrame:CGRectMake(7*Radio, iPhoneX ? 35*Radio-5 : 35*Radio-3, 2.6, 2.6)];
        _footView.backgroundColor = RGB(134, 137, 147, 1);
        _footView.layer.cornerRadius = 1.3;
        _footView.layer.masksToBounds = YES;
    }
    return _footView;
}

//初始化
+ (instancetype)sharedInstance {
    static MJ_UserMessage *message = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        message = [[MJ_UserMessage alloc] init];
    });
    return message;
}

//跳转信息列表
- (void)message {
    MessageViewController *messageController = [[MessageViewController alloc] init];
    TGLog(@"当前控制器---------------------%@",[UIViewController currentViewController]);
    MMDrawerController *currentVC = (MMDrawerController *)[UIViewController currentViewController];
    
    if ([currentVC.centerViewController isKindOfClass:[UITabBarController class]]) {
        
        TabbarController *tab = (TabbarController *)currentVC.centerViewController;
        NavigationController *nav = (NavigationController *)tab.selectedViewController;
        [nav pushViewController:messageController animated:YES];
        
    }else{
        NavigationController *nav = (NavigationController *)currentVC.centerViewController;
        [nav pushViewController:messageController animated:YES];
    }
}

//打开抽屉
- (void)openLeftController {
    TGLog(@"当前控制器---------------------%@",[UIViewController currentViewController]);
    MMDrawerController *currentVC = (MMDrawerController *)[UIViewController currentViewController];
    [currentVC toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (MMDrawerController *)setupEnterpriseRootVC {
    
    LeftSortsViewController* left = [[LeftSortsViewController alloc] init];
    TabbarController *tabbar = [[TabbarController alloc]init];
    [tabbar setRestorationIdentifier:@"MMExampleCenterNavigationControllerRestorationKey"];
    [left setRestorationIdentifier:@"MMExampleLeftNavigationControllerRestorationKey"];
    MMDrawerController *vc = [[MMDrawerController alloc] initWithCenterViewController:tabbar leftDrawerViewController:left];
    vc.maximumLeftDrawerWidth = Screen_Width/5.0*4.0;
    vc.openDrawerGestureModeMask = MMOpenDrawerGestureModeAll;
    vc.closeDrawerGestureModeMask = MMCloseDrawerGestureModeAll;
    self.currentDrawerController = vc;
    return vc;
}

- (MMDrawerController *)setupPriviteRootVC {
    LeftSortsViewController* left = [[LeftSortsViewController alloc] init];
    MJ_TaskViewController *taskVC = [[MJ_TaskViewController alloc]init];
    NavigationController *navi = [[NavigationController alloc] initWithRootViewController:taskVC];
    MMDrawerController *vc = [[MMDrawerController alloc] initWithCenterViewController:navi leftDrawerViewController:left];
    vc.maximumLeftDrawerWidth = Screen_Width/5.0*4.0;
    vc.openDrawerGestureModeMask = MMOpenDrawerGestureModeAll;
    vc.closeDrawerGestureModeMask = MMCloseDrawerGestureModeAll;
    self.currentDrawerController = vc;
    return vc;
}



- (void)userOnline {
    [UserDefaults setBool:YES forKey:@"IsOnline"];
}

- (void)userLogOut {
    
    [UserDefaults setBool:NO forKey:@"IsOnline"];
    [UserDefaults removeObjectForKey:@"account"];
    [UserDefaults removeObjectForKey:@"password"];
    [UserDefaults setBool:NO forKey:@"unreadMessage"];
    [UserDefaults removeObjectForKey:@"User_Cookie"];
    [UserDefaults removeObjectForKey:CurrentUserTypeKey];
    [UserDefaults removeObjectForKey:@"searchHistory"];
    [UserDefaults removeObjectForKey:@"timeRange"];//移除登录超时统计数据
}

- (BOOL)userIsOnline {
    return [UserDefaults boolForKey:@"IsOnline"];
}
//显示小红点,新消息提醒
- (void)showBadgeWithMessageButton{
    [self.messageBarButton yee_MakeBadgeText:@"" textColor:[UIColor whiteColor] backColor:[UIColor redColor] Font:[UIFont systemFontOfSize:10]];
}
//隐藏小红点
- (void)hideBadgeWithMessageButton{
    [self.messageBarButton removeBadgeView];
}


- (void)checkAppVersion {
    
    [AvailableNetWorking postWithUrl:APP_VERSION params:@{@"model":@"1"} successHandler:^(id responseObject) {
        TGLog(@"%@",responseObject);
        if (responseObject[@"code"] && [responseObject[@"code"] integerValue] == 200) {
            MJVersionCheckModel *versionModel = [MJVersionCheckModel mj_objectWithKeyValues:responseObject];
            MJResultModel *resultModel = versionModel.result;
            //线上版本号(去掉了中间的.)，后台返回
            NSString *resultVersion = [resultModel.version stringByReplacingOccurrencesOfString:@"." withString:@""];
            //当前版本号(去掉了中间的.)
            NSString *version = [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] stringByReplacingOccurrencesOfString:@"." withString:@""];//获取项目版本号
            TGLog(@"app store version = %@ ,project version = %@",resultVersion,version);
            if (resultVersion.integerValue > version.integerValue) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"版本更新" message:@"译马网发布新版本啦，更快更稳定,快去下载吧" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"马上前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/cn/app/id1206278209?mt=8"]];
                }];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleDefault handler:nil];
                
                if (resultModel.mandatory == 1) {
                    //强制update
                    [alertController addAction:sureAction];
                    [[UIViewController currentViewController] presentViewController:alertController animated:YES completion:nil];
                }else{
                    //非强制update
                    [alertController addAction:sureAction];
                    [alertController addAction:cancelAction];
                    [[UIViewController currentViewController] presentViewController:alertController animated:YES completion:nil];
                }
            }
        }
    } falureHandler:^(NSError *error) {
        
    }];
}

- (void)saveDeviceTokenWithString:(NSString *)deviceToken {
    [UserDefaults setObject:deviceToken forKey:@"deviceToken"];
}
- (NSString *)getDeviceToken {
    NSString *deviceToken = [UserDefaults objectForKey:@"deviceToken"];
    if (deviceToken == nil) {
        //如果获取失败，先传一个uuid
        NSString *uuidString = [[[UIDevice currentDevice].identifierForVendor UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
        deviceToken = uuidString;
    }
    return deviceToken;
}
@end
